package com.mission.shaco.warehouse.stockin

import android.os.Build
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import com.androidquery.AQuery
import com.androidquery.callback.AjaxCallback
import com.androidquery.callback.AjaxStatus

import com.mission.shaco.warehouse.R
import com.mission.shaco.warehouse.ScannerActivity
import com.mission.shaco.warehouse.models.ClientConfig
import com.mission.shaco.warehouse.models.Tool
import kotlinx.android.synthetic.main.activity_check_qty.*
import kotlinx.android.synthetic.main.activity_stock_in.*
import org.json.JSONArray
import org.json.JSONObject

class StockInActivity : ScannerActivity() {

    var stockLogList =  JSONArray()
    var lastStockId :String = ""

    var loadThread: Runnable = Runnable {
        try {
            val aq: AQuery = AQuery(this)
            val params = HashMap<String, Any>()

            var map = JSONObject()
            map.put("webItemId",txtSKU.text)
            params.put("datas",map)

            aq.ajax(ClientConfig.getHostUrl(ClientConfig.JSON_GET_STOCK_IN_INFO), params,String::class.java, object : AjaxCallback<String>() {

                override fun callback(url: String, result: String, status: AjaxStatus) {
                    if(status.code == 200){
                        var response: JSONObject = JSONObject(result)

                        if(response.getInt("status") == ClientConfig.RESPONSE_STATUS_SUCCESS) {
                            var info = response.getJSONObject("info")
                            txtRealStockId.text = info.getString("position")
                            stockLogList = info.getJSONArray("checkDetail")
                            txtRealQty.text = info.getString("StockCount")
                            successNotice()
                            txtStockId.requestFocus()
                            reloadShow()
                        }else {
                            noticeMessage(response.getString("msg"))
                            clear()
                        }

                    }else{

                    }
                }
            })

        } catch (e: InterruptedException) {
            e.printStackTrace()
        }
    }


    fun reloadShow(){
        var len = stockLogList.length()
        var show = ""
        for (i in 0..len -1){
            var item = stockLogList.getJSONObject(i)
            show+= "数量:" + item.getString("checkQty")+"       " + item.getString("checkTime")+"\r\n"
        }
        txtLogShow.setText(show)
        var item = stockLogList.getJSONObject(0)
        txtStockInCount.setText(item.getString("checkQty"))
    }

    fun removeFirst(){
        if(stockLogList.length() > 0) {
            if (Build.VERSION.SDK_INT < 19) {
                stockLogList = Tool().JSONRemove(0, stockLogList)
            } else {
                stockLogList.remove(0)
            }
        }
    }

    var stockInThread: Runnable = Runnable {
        try {
            val aq: AQuery = AQuery(this)
            val params = HashMap<String, Any>()

            var map = JSONObject()
            map.put("webItemId",txtSKU.text)
            map.put("picker",opreateName)
            map.put("qty",txtStockInCount.text.toString())
            map.put("checkId", stockLogList.getJSONObject(0).getString("id"))
            var oldQty = Integer.parseInt(txtStockInCount.text.toString())

            map.put("type","1")

            params.put("datas",map)

            aq.ajax(ClientConfig.getHostUrl(ClientConfig.JSON_GET_STOCK_IN_COMPLETE), params,String::class.java, object : AjaxCallback<String>() {

                override fun callback(url: String, result: String, status: AjaxStatus) {
                    if(status.code == 200){
                        var response: JSONObject = JSONObject(result)

                        if(response.getInt("status") == ClientConfig.RESPONSE_STATUS_SUCCESS) {
                            noticeMessage("上架操作成功")
                            reloadShow()
                            if(stockLogList.length()==1){
                                clear()
                            }else{
                                var t  = Thread(loadThread)
                                t.start()
                            }
                        }else {
                            noticeMessage(response.getString("msg"))
                        }

                    }else{

                    }
                }
            })

        } catch (e: InterruptedException) {
            e.printStackTrace()
        }
    }

    fun clear(){
        txtSKU.setText("")
        txtStockId.setText("")
        txtStockInCount.setText("")
        txtRealStockId.setText("")
        btnStockIn.isEnabled = false
        lastStockId = ""
        txtLogShow.setText("")
        txtRealQty.setText("")
    }




    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_stock_in)

        button.setOnClickListener(this)
        btnStockIn.setOnClickListener(this)
        btnClear.setOnClickListener(this)

        txtSKU.isEnabled = false
        txtStockId.isEnabled = false
        btnStockIn.isEnabled = false
        txtStockInCount.isEnabled = false

        if(ClientConfig.TestModel) {
            button.visibility = View.VISIBLE
            txtSKU.isEnabled = true
        }
    }

    override fun onClick(v: View?) {
        when(v?.id){
            button.id -> {  var t = Thread(loadThread); t.start() }
            btnStockIn.id -> { var t  = Thread(stockInThread); t.start() }
            btnClear.id -> { clear() }
        }
    }



    override fun afterScanReceive() {
        if(!isCurrentClass()) return

        if(!TextUtils.isEmpty(code)) {
            if(TextUtils.isEmpty(txtSKU.text)){
                txtSKU.setText(code)
                var t = Thread(loadThread)
                t.start()
            }else if (txtStockId.isFocused()){
                if(code == txtRealStockId.text ){
                    txtStockId.setText(code)
                    txtStockInCount.requestFocus()
                    if(stockLogList.length() >=1 ) {
                        btnStockIn.isEnabled = true
                    }
                    successNotice()
                    lastStockId = code
                }else{
                    noticeMessage("库位号不匹配,不能进行上架操作.")
                }
            }
        }

        code = ""
    }


    /**
     *  配货匹配成功提示
     */
    fun successNotice(){
        player.start()
        vibrator.vibrate(800)
    }
}
